package com.sinvo.oa.service.impl;

import com.sinvo.oa.custom.CustomUser;
import com.sinvo.oa.entity.model.system.SysUser;
import com.sinvo.oa.service.SysMenuService;
import com.sinvo.oa.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 重写Spring Security中的查询方法
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询
        SysUser sysUser = sysUserService.findUserByUserName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        if (sysUser.getStatus() == 0) {
            throw new RuntimeException("账号已停用");
        }
        //查询用户操作权限数据
        List<String> userPermsList = sysMenuService.findUserPermsByUserId(sysUser.getId());
        //Collection<? extends GrantedAuthority> authorities
        //封装最终权限数据
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        for (String perm : userPermsList) {
            authorityList.add(new SimpleGrantedAuthority(perm.trim()));
        }
        return new CustomUser(sysUser, authorityList);
    }
}
